<template>
  <el-form ref="form"
           class="update-app-form"
           label-position="top"
           label-width="80px"
           :rules="rules"
           :model="form">
    <template v-if="step===0">
      <el-form-item label="Name"
                    prop="name">
        <el-input v-model="form.name"
                  placeholder="Please Enter"
                  clearable></el-input>
      </el-form-item>
      <el-form-item label="Description">
        <el-input type="textarea"
                  resize="none"
                  :rows="3"
                  v-model="form.description"
                  placeholder="Please Enter"
                  clearable></el-input>
      </el-form-item>
      <el-form-item label="Help and feedback URL">
        <el-input v-model.trim="form.instructions"
                  placeholder="Please Enter"
                  clearable></el-input>
      </el-form-item>
      <el-form-item prop="period"
                    :label="$t('custom.dataset.status')">
        <el-select v-model="form.period"
                   :placeholder="$t('custom.dataset.status')">
          <el-option v-for="item in statusList"
                     :key="item.value"
                     :label="item.label"
                     :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="da"
                    :label="$t('custom.report.da')">
        <el-select v-model="form.da"
                   clearable
                   filterable
                   :placeholder="$t('custom.report.da')">
          <el-option v-for="item in users"
                     :key="item.id"
                     :label="item.realname"
                     :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="po"
                    :label="$t('custom.report.po')">
        <el-select v-model="form.po"
                   clearable
                   filterable
                   :placeholder="$t('custom.report.po')">
          <el-option v-for="item in users"
                     :key="item.id"
                     :label="item.realname"
                     :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="jiraNumber"
                    :label="$t('custom.reports.jiraNumber')">
        <el-input v-model="form.jiraNumber"
                  type="text"
                  rows="3"
                  :placeholder="$t('custom.reports.jiraNumber')">
          <JiraNumberLink slot="suffix"
                          :jiraNumber="form.jiraNumber" />
        </el-input>
      </el-form-item>
      <el-form-item label="Icon"
                    prop="fileInfo">
        <el-upload action=""
                   class="upload-icon"
                   :on-change='changeUpload'
                   :auto-upload="false"
                   :show-file-list="false">
          <div class="upload-icon__content flex">
            <div class="upload-icon__content-left">
              <img :src="form.picture"
                   alt="">
            </div>
            <div class="upload-icon__content-right">
              <div class="upload-icon__content-right--tip">120*120px, only supports PNG format, and the file is less than or equal to 5 MB.</div>
              <el-button size="mini"
                         type="primary"
                         style="margin-top:12px">Upload</el-button>
            </div>
          </div>
        </el-upload>
      </el-form-item>
    </template>
    <template v-if="step===1">
      <el-form-item>
        <BChargeCatalog :chargeCatalogs="form.chargeCatalogs"
                        :family.sync="form.family"
                        :products="products" />
      </el-form-item>
      <el-form-item label="App">
        <el-select v-model="form.type"
                   clearable>
          <el-option v-for="record in appTypes"
                     :label="record.label"
                     :value="record.value"
                     :key="record.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="Banner">
        <ZUpload v-model="form.banner" />
      </el-form-item>
      <el-form-item label="Sort">
        <el-input-number controls-position="right"
                         v-model="form.sort" />
      </el-form-item>
      <el-form-item label="Pay Mode">
        <el-select v-model="form.userLimit">
          <el-option v-for="item in payMode"
                     :key="item.value"
                     :label="item.label"
                     :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('attribute.rules')">
        <BRules v-model="form.sysPaywallList" />
      </el-form-item>
    </template>
    <template v-if="step === 2">
      <BConfigResource title="Dashboards"
                       rTitle="Dashboards"
                       component="Dashboards"
                       isUrl
                       v-model="form.dashboards"
                       :resourceType="1"
                       :resourceMenu="1" />
      <BConfigResource title="Bots"
                       rTitle="Bots"
                       component="Bots"
                       v-model="form.bots"
                       :resourceType="2"
                       :resourceMenu="2" />

      <BConfigResource title="Settings"
                       rTitle="Settings"
                       component="Settings"
                       isUrl
                       v-model="form.settings"
                       :resourceType="1"
                       :resourceMenu="3" />
    </template>
    <template v-if="step === 3">
      <el-form-item label="Version Number"
                    prop="appVersion">
        <el-cascader v-model="form.appVersion"
                     separator="."
                     :props="{ expandTrigger: 'hover' }"
                     :options="versions"></el-cascader>
      </el-form-item>
      <el-form-item label="Version Description">
        <el-input type="textarea"
                  resize="none"
                  :rows="3"
                  v-model="form.upgradeDesc"
                  placeholder="Please Enter"
                  clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-table max-height="240"
                  :show-header="false"
                  :data="history"
                  style="width: 100%;border:1px solid #DCDFE6">
          <el-table-column type="expand">
            <template slot-scope="scope">
              <el-form label-position="left"
                       inline
                       class="demo-table-expand">
                <el-form-item>
                  <span>{{scope.row.submitDesc}}</span>
                </el-form-item>
              </el-form>
            </template>
          </el-table-column>
          <el-table-column prop="appVersion">
          </el-table-column>
          <el-table-column>
            <template slot-scope="scope">
              {{formatDate( scope.row.updateTime,'MM/DD/YYYY HH:mm')}}
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
    </template>

    <el-dialog :visible.sync="clipVisible"
               destroy-on-close
               append-to-body>
      <div class="cropper-content">
        <div class="cropper"
             style="text-align:center">
          <vueCropper ref="cropper"
                      :img="file"
                      v-bind="cropper" />
        </div>
      </div>
      <div slot="footer"
           class="dialog-footer">
        <el-button size="mini"
                   @click="closeClipDialog">Cancel</el-button>
        <el-button size="mini"
                   type="primary"
                   :loading="uploadLoading"
                   @click="handleUploadIcon">Confirm</el-button>
      </div>
    </el-dialog>
  </el-form>
</template>

<script>
import { statusList, payMode, cropper, icon } from './index.schema'
import JiraNumberLink, { JiraNumberMixin } from '@/components/jira-number-link'
import BChargeCatalog from '@/components/storybook/b-charge-catalog/index'
import { appTypes } from '@/components/storybook/settings/chargebee'
import ZUpload from '@/components/storybook/z-upload/index'
import BRules from '@/components/storybook/b-rules/index'
import BConfigResource from '@/components/storybook/b-config-resource/index'
import { get, groupBy } from 'lodash'
import useBlob from '@/components/storybook/hooks/useBlob'
import useCharge from '@/components/storybook/hooks/useCharge'
import { GlobalTimeformat } from '@/utils/common'

export default {
  name: 'UpdateAppForm',
  components: { JiraNumberLink, BChargeCatalog, ZUpload, BRules, BConfigResource },
  mixins: [JiraNumberMixin],
  props: {
    loading: Boolean,
    step: {
      type: Number,
      default: 0
    },
    id: [String, Number],
    version: [String, Number]
  },
  data () {
    const validateStatus = (rule, value, callback) => {
      if (this.$store.state.user.username.includes('mspbots.ai') && !value) {
        callback(new Error('Please select Status'))
        return
      }
      callback()
    }
    const validateDa = (rule, value, callback) => {
      if (this.$store.state.user.username.includes('mspbots.ai') && !value) {
        callback(new Error(this.$t('custom.component.gadget.da')))
        return
      }
      callback()
    }
    const validatePo = (rule, value, callback) => {
      if (this.$store.state.user.username.includes('mspbots.ai') && !value) {
        callback(new Error(this.$t('custom.component.gadget.po')))
        return
      }
      callback()
    }
    const validateJira = async (rule, value, callback) => {
      const isMatchJiraNumber = await this.checkJiraNumber(value)

      if (this.$store.state.user.username.includes('mspbots.ai') && !isMatchJiraNumber) {
        callback(new Error(this.$t('custom.component.gadget.checkNumber')))
        return
      }
      callback()
    }
    const validatePass = async (rule, value, callback) => {
      const { postValidateNameApi } = this.$interface.reports
      const params = {
        id: this.form.id,
        name: value
      }
      let { data: response } = await postValidateNameApi(params)

      if (response.code !== 0) {
        callback(new Error(response.msg))
        return
      }
      callback()
    }
    return {
      statusList,
      appTypes,
      payMode,
      cropper,
      versions: [],
      users: [],
      history: [],
      products: [],
      clipVisible: false,
      icon,
      form: {
        picture: icon,
        appVersion: [],
        chargeCatalogs: [],
        dashboards: [],
        bots: [],
        settings: [],
        name: undefined,
        family: undefined
      },
      file: undefined,
      uploadLoading: false,
      rules: {
        name: [
          { required: true, message: 'Cannot be empty', trigger: 'blur', pattern: '[^ \x22]+' },
          { min: 3, max: 48, message: 'The length is between 3 and 48 characters', trigger: 'blur' },
          { validator: validatePass, trigger: 'blur' }
        ],
        period: [{ required: true, validator: validateStatus, trigger: 'change' }],
        da: [{ required: true, validator: validateDa, trigger: 'change' }],
       // po: [{ required: true, validator: validatePo, trigger: 'change' }],
       // jiraNumber: [{ required: true, validator: validateJira, trigger: 'blur' }],
        appVersion: [
          { type: 'array', required: true, message: 'Cannot be empty', trigger: 'change' }
        ]
      }
    }
  },
  created () {
    this.init()
  },
  watch: {
    step () {
      this.$refs['form'].clearValidate()
    }
  },
  methods: {
    async init () {
      try {
        this.$emit('update:loading', true)
        const [users, versions, products, app, history] = await Promise.all([this.getUserList(), this.getVersions(), this.getProducts(), this.getApp(), this.getHistory()])
        let { itemId, chargebeeItemFamilies, appVersion, appResourceList, sysPaywallList } = app
        const item = products.find(i => i.otherId === get(chargebeeItemFamilies, 'otherId'))
        this.users = users
        this.versions = versions
        this.products = products
        this.form = Object.assign({}, this.form, app)
        const family = products.find(i => i.otherId === get(chargebeeItemFamilies, 'otherId'))
        if (family) {
          this.form.family = family
        }
        this.form.sysPaywallList = sysPaywallList || []
        if (appVersion) {
          this.form.appVersion = appVersion.split('.').map(i => Number(i))
        }

        if (appResourceList && appResourceList.length) {
          const groupResource = groupBy(appResourceList, 'resourceMenu')
          this.form.dashboards = groupResource['1'] || []
          this.form.bots = groupResource['2'] || []
          this.form.settings = groupResource['3'] || []
          this.form.widgets = groupResource['4'] || []
          this.form.datasets = groupResource['5'] || []
        }

        if (item && item.chargebeeItems && item.chargebeeItems.length) {
          this.form.chargeCatalogs = useCharge(itemId, item.chargebeeItems)
        }
        this.history = history
      } catch (error) {
      } finally {
        this.$emit('update:loading', false)
      }
    },
    async changeUpload (file) {
      this.clipVisible = true
      this.file = await useBlob(file.raw)
    },
    formatDate (time, str) {
      return GlobalTimeformat(time, 'HH:mm')
    },
    closeClipDialog () {
      this.form.picture = icon
      this.file = undefined
      this.clipVisible = false
    },
    async handleUploadIcon () {
      try {
        this.uploadLoading = true
        const { postUploadImg } = this.$interface.system

        const paramsUpload = {
          file: this.file,
          path: 'apps',
          bucket: 'bots'
        }
        const { data: response } = await postUploadImg(paramsUpload)
        if (response.code !== 0) {
          throw response.msg
        }
        this.form.picture = get(response, 'data.src')
        this.file = undefined
        this.clipVisible = false
      } catch (error) {

      } finally {
        this.uploadLoading = false
      }
    },

    async getUserList () {
      const { getDrillThroughDataInfo } = this.$interface.reports
      const params = {
        datasetKey: 'qwerdsafsadrtfzgsadfggs'
      }
      let { data: response } = await getDrillThroughDataInfo(params)
      if (response.code !== 0) {
        throw response.msg
      }
      return response.data
    },
    async getApp () {
      const { getAppInfoApi } = this.$interface.reports
      const params = {
        id: this.id
      }
      let { data: response } = await getAppInfoApi(params)
      if (response.code !== 0) {
        throw response.msg
      }
      return response.data
    },
    async getHistory () {
      const { getVersionListApi } = this.$interface.reports

      const params = {
        appId: this.id
      }
      let { data: response } = await getVersionListApi(params)
      if (response.code !== 0) {
        throw response.msg
      }

      return response.data
    },
    async getVersions () {
      const { getSelectListApi } = this.$interface.reports

      const params = {
        version: this.version
      }
      let { data: response } = await getSelectListApi(params)
      if (response.code !== 0) {
        throw response.msg
      }

      return response.data
    },
    async getProducts () {
      const { productFamilies } = this.$interface.pay

      const params = {
        status: 'active'
      }
      let { data: response } = await productFamilies(params)

      if (response.code !== 0) {
        throw response.msg
      }
      return response.data || []
    },
    async onSave () {
      try {
        this.$emit('update:loading', true)
        const { putUpdateAppsApi } = this.$interface.reports

        await this.$refs['form'].validate()

        const { appVersion, chargeCatalogs, dashboards, bots, settings, ...rest } = this.form
        const itemId = chargeCatalogs.reduce((result, record) => ([...result, ...record.chargebeeItemPricesList.map(i => i.otherId)]), []).join()
        const params = {
          ...rest,
          appVersion: appVersion.join('.'),
          itemId,
          appResourceList: [...dashboards, ...bots, ...settings]
        }
        let { data: response } = await putUpdateAppsApi(params)
        if (response.code !== 0) {
          throw response.msg
        }
        this.$message.success('Update Success')
        this.$emit('success')
        this.$emit('update:loading', false)
      } catch (error) {
        this.$message.error('Verification failed')
      } finally {
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.upload-icon {
  &__content {
    &-left {
      width: 80px;
      height: 80px;
      margin-right: 10px;
      img {
        width: 60px;
        height: 60px;
        margin-top: 10px;
        border-radius: 4px;
      }
    }
    &-right {
      height: 80px;
      text-align: left;
      &--tip {
        font-size: 12px;
        color: #808080;
        line-height: 18px;
      }
      .el-button {
        margin-top: 12px;
      }
    }
  }
}

.el-select {
  width: 100%;
}

.cropper-content {
  .cropper {
    width: auto;
    height: 300px;
  }
}
</style>
